var prefix = jsctx + "/operator";

var operator = (function () {
    function init() {
        load();
    };

    $('#exampleTable').on('load-success.bs.table', function (e, data) {
        if (data.total && !data.rows.length) {
            $('#exampleTable').bootstrapTable('selectPage').bootstrapTable('refresh');
        }
    });

    /**
     * 导出列表
     */
    function exportList() {
        $.fileDownload(prefix + "/export", { // 后台请求链接
            httpMethod: "get",　　　　　　　　// 请求方式
            contentType: 'application/json',　 // 请求头
            data: {　　　　　　　　　　　　　　　// 参数，左边为后台接收的参数名，右边为前端获取的值，
                operatorName: $("#operatorName").val(),
                offset: $('.active .page-link').text(),
                limit: $(".page-size").text()
            },
            prepareCallback: function (url) {
                layer.msg("文件下载中...", {time: -1})
            },
            abortCallback: function (url) {
                // 异常终止
                layer.msg("文件下载异常！！");
            },
            successCallback: function (url) {
                layer.msg("文件下载成功！！", {time: 1500});
            },
            failCallback: function (data) {
                var str = "{" + data.substring(data.indexOf("{") + 1, data.indexOf("}")) + "}";
                layer.msg(JSON.parse(str).message);
            }
        })
    }

    var h = $(window).height() - 80;

    function load() {
        $('#exampleTable')
            .bootstrapTable(
                {
                    method: 'get',
                    url: prefix + "/listPageOperator",
                    iconSize: 'outline',
                    toolbar: '#exampleToolbar',
                    striped: false,
                    dataType: "json",
                    pagination: true,
                    singleSelect: false,
                    pageSize: 10,
                    pageList: [10],
                    pageNumber: 1,
                    sidePagination: "server",
                    queryParams: function (params) {
                        return {
                            pageSize: params.limit,
                            pageNo: (params.offset / params.limit) + 1,
                            operatorName: $("#operatorName").val()
                        };
                    },
                    columns: [
                        {
                            title: '序号', field: '', width: '50', align: 'left',
                            formatter: function (value, row, index) {
                                return index + 1;
                            }
                        },
                        {field: 'operatorId', title: '加盟商ID', width: '100', align: 'left'},
                        {field: 'operatorName', title: '加盟商名称', width: '100', align: 'left'},
                        {field: 'enterpriseName', title: '所属企业', width: '100', align: 'left'},
                        {
                            field: 'operatorType', title: '类型', width: '100', align: 'left',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '自营';
                                } else if (value == '1') {
                                    return '托管';
                                } else if (value == '2') {
                                    return '加盟';
                                } else if (value == '3') {
                                    return '接口';
                                }

                            }

                        },
                        {field: 'contactName', title: '负责人', width: '100', align: 'left'},
                        {field: 'phone', title: '联系电话', width: '100', align: 'left'},
                        {field: 'createdTime', title: '创建时间', width: '100', align: 'left'},
                        {
                            field: 'applyStatus',
                            title: '审核状态',
                            width: '100', align: 'center',
                            formatter: function (value, row, index) {
                                if (value == '0') {
                                    return '<span class="label label-success">待审核</span>';
                                } else if (value == '1') {
                                    return '<span class="label label-info">审核通过</span>';
                                } else if (value == '2') {
                                    return '<span class="label label-danger">审核未通过</span>';
                                }
                            }
                        },
                        {
                            title: '操作',
                            field: 'roleId',
                            width: '150', align: 'center',
                            formatter: function (value, row, index) {
                                var operate = "";
                                var a = '<a class="btn btn-primary btn-sm' + has_edit + '" href="#" title="审核" onclick="operator.showModel(\''
                                    + row.operatorId + '\',\''+ row.phone +'\')">审核</a> ';
                                var b = '<a class="btn btn-success btn-sm' + has_edit + '" href="#" title="编辑" onclick="operator.edit(\''
                                    + row.operatorId + '\')">编辑</a> ';
                                var c = '<a class="btn btn-warning btn-sm' + has_edit + '" href="#" title="详情" onclick="operator.detail(\''
                                    + row.operatorId + '\')">详情</a> ';
                                var d = '<a class="btn btn-danger btn-sm ' + has_edit + '" href="#" title="删除" onclick="operator.delete(\''
                                    + row.operatorId + '\')">删除</a> ';
                                var e = '<a class="btn btn-primary btn-sm' + has_edit + '" href="#" title="发票额度" onclick="operator.showInvoiceModel(\''
                                    + row.operatorId + '\')">发票额度</a> ';
                                if (row.applyStatus == '0') {
                                    operate = operate + a + b;
                                }
                                operate = operate + c + d;
                                if (row.applyStatus == '1') {
                                    operate = operate + e;
                                }

                                return  operate;

                            }
                        }
                    ]
                });
    }


    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
        load();
    }

    function add() {
        location.href = prefix + "/add";
    }

    function edit(id) {
        location.href = prefix + "/edit/" + id;
    }

    function detail(id) {
        location.href = prefix + "/detail/" + id;
    }

    function deleteOperator(id) {
        layer.confirm('确定要删除选中的记录？', {
            btn: ['确定', '取消']
        }, function (index) {
            $.ajax({
                url: prefix + "/delete",
                type: "post",
                data: {
                    'id': id
                },
                success: function (data) {
                    layer.close(index);
                    if (data.status == 200) {
                        layer.msg("删除成功");
                        reLoad();
                    } else {
                        layer.msg(data.message);
                    }
                }
            });
        })
    }


    function goBack() {
        window.history.back();
    }



    /*  模态框  */
    function showModel(id, mobile) {
        $('#exampleModal').modal('show');
        var memberId = null;
        var status = $("#status").val();




        $("#submitButton").unbind("click").bind("click", function () {
            if ('1' == status) {
                $.ajax({
                    url: prefix + "/addMember",
                    type: "post",
                    data: {
                        "mobile": mobile,
                    },
                    dataType: "json",
                    success: function (data) {
                        if (data.status == 200) {
                            memberId = data.data;
                        }
                    }
                })
            }

            setTimeout(function () {
                $.ajax({
                    url: prefix + "/updateOperatorApplyForAudit",
                    type: "post",
                    data: {
                        "id": id,
                        "memberId":memberId,
                        "status": status,
                        "remark": $("#remark").val()
                    },
                    dataType: "json",
                    success: function (data) {
                        if (data.status == 200) {
                            parent.layer.msg("操作成功");
                            $('#exampleModal').on('hidden.bs.modal', function () {
                                document.getElementById("contentForm").reset();
                            })
                            $('#exampleModal').modal('hide')
                            reLoad();
                        } else {
                            parent.layer.alert(data.message);
                            $('#exampleModal').on('hidden.bs.modal', function () {
                                document.getElementById("contentForm").reset();
                            })
                            $('#exampleModal').modal('hide')
                        }
                    }
                })
            }, 2000)



        })

    }

    function showInvoiceModel(id) {
        $('#invoiceModal').modal('show');

        $("#submitInvoice").unbind("click").bind("click", function () {
            $.ajax({
                url: prefix + "/updateOperatorForInvoice",
                type: "post",
                data: {
                    "id": id,
                    "invoiceDateType": $("#invoiceDateType").val(),
                    "invoiceSingleMaxAmount": $("#invoiceSingleMaxAmount").val(),
                    "invoiceMaxAmount": $("#invoiceMaxAmount").val(),
                    "invoiceEachMaxGet": $("#invoiceEachMaxGet").val(),
                    "invoiceMaxGet": $("#invoiceMaxGet").val()
                },
                dataType: "json",
                success: function (data) {
                    if (data.status == 200) {
                        parent.layer.msg("操作成功");
                        $('#invoiceModal').on('hidden.bs.modal', function () {
                            document.getElementById("invoiceForm").reset();
                        })
                        $('#invoiceModal').modal('hide')
                        reLoad();
                    } else {
                        parent.layer.alert(data.message);
                        $('#invoiceModal').on('hidden.bs.modal', function () {
                            document.getElementById("invoiceForm").reset();
                        })
                        $('#invoiceModal').modal('hide')
                    }
                }
            })
        })

    }

    return {
        init: init,
        goBack: goBack,
        reLoad: reLoad,
        add: add,
        edit: edit,
        showModel: showModel,
        detail: detail,
        delete: deleteOperator,
        exportList: exportList,
        showInvoiceModel:showInvoiceModel
    };
})();

var addOperator = (function () {
    function init() {
        validateRule();
    };

    function reLoad() {
        $('#exampleTable').bootstrapTable('refresh');
    }


    var isajaxsend = true;

    function save() {
        var formData = new FormData($("#frm")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/saveOperator",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            beforeSend: function () {
                isajaxsend = false
            },
            error: function (request) {
                parent.layer.alert("Connection error");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("操作成功");
                    location.href = prefix + "/index";
                } else {
                    parent.layer.alert(data.message)
                }

            },
            complete: function () {
                isajaxsend = false
            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                operatorName: {
                    required: true,
                },
                contactName: {
                    required: true,
                }, phone: {
                    required: true,
                }
            },
            messages: {
                operatorName: {
                    required: icon + "请输入加盟商名称"
                },contactName: {
                    required: icon + "请输入负责人"
                },phone: {
                    required: icon + "请输入联系电话"
                }
            },
            submitHandler: function (form) {
                save();
            }
        })
    }

    return {
        init: init
    };
})();

var editOperator = (function () {
    function init() {
        validateRule();
    };


    var isajaxsend = true;

    function save() {
        var formData = new FormData($("#frm")[0]);
        $.ajax({
            cache: true,
            type: "POST",
            url: prefix + "/saveOperator",
            data: formData,
            processData: false,
            contentType: false,
            async: false,
            error: function (request) {
                parent.layer.alert("失败");
            },
            success: function (data) {
                if (data.status == 200) {
                    parent.layer.msg("成功");
                    location.href = prefix + "/index";
                } else {
                    parent.layer.alert(data.message);
                }
            }
        });
    }

    function validateRule() {
        var icon = "<i class='fa fa-times-circle'></i> ";
        $("#frm").validate({
            rules: {
                operatorName: {
                    required: true,
                },
                contactName: {
                    required: true,
                }, phone: {
                    required: true,
                }
            },
            messages: {
                operatorName: {
                    required: icon + "请输入加盟商名称"
                },contactName: {
                    required: icon + "请输入负责人"
                },phone: {
                    required: icon + "请输入联系电话"
                }
            },
            submitHandler: function (form) {
                save();
            }
        });
    }

    return {
        init: init
    };
})();

